<?php

use Rootant\Api\Exception\ValidationException;

/**
 * 复用控制器
 *
 */
class MultiplexController extends Controller
{
    const CSP_URL = 'http://m.csapchina.com';

    /**
     * 公共的返回文章相关信息的静态方法
     *
     * @return object Illuminate\Database\Query\Builder
     */
    public static function article()
    {
        $article = DB::connection('secondly')->table('article')
            ->select('id', 'aid', 'thumbnail_url', 'title', 'origin', 'author', 'created_at');

        return $article;
    }

    /**
     * 公共的返回用户相关信息的静态方法
     *
     * @return Illuminate\Database\Query\Builder
     */
    public static function user()
    {
        $user = DB::connection('secondly')->table('user')
            ->select('id', 'uuid', 'name', 'avatar_url', 'gender', 'created_at', 'updated_at');

        return $user;
    }

    /**
     * [getOwner description]
     *
     * @param  int    $userId
     * @param  string $userIp
     * @return object|array
     */
    public static function getOwner($userId, $userIp)
    {
        if ($userId !== null) {
            // 返回用户信息
            return self::getUser($userId);
        }
        // 返回匿名用户信息
        return self::anonymousUser($userIp);
    }

    /**
     * 增加数据模型分页
     *
     * @param  object $model 需要分页的数据模型
     * @return void
     */
    public static function addPagination($model)
    {
        // 第几页数据，默认为第一页
        $page    = Input::get('page', 1);
        // 每页显示数据条目，默认为每页20条数据
        $perPage = Input::get('per_page', 20);
        $page    = intval($page);
        $perPage = intval($perPage);

        if ($page <= 0 || !is_int($page)) {
            $page = 1;
        }
        if (!is_int($perPage) || $perPage < 1 || $perPage > 100) {
            $perPage = 20;
        }
        // skip -- offset , take -- limit
        $model->skip(($page - 1) * $perPage)->take($perPage);
    }

    /**
     * soap web service util
     *
     * @return object SoapClient
     */
    public static function getWebServiceClient()
    {
        $url = 'http://manage.chinashippinginfo.net/csiInterface/InteShipping.asmx?wsdl';
        $options = array('trace' => true, 'exceptions' => true);

        return new SoapClient($url, $options);
    }

    /**
     * 获取用户信息
     *
     * @param  int    $uid
     * @return object stdClass
     */
    public static function getUser($uid)
    {
        $key = 'users/'.$uid;
        if (Cache::has($key)) {
            return Cache::get($key);
        }

        $userInfo = self::user()->find($uid);

        $soapClient = self::getWebServiceClient();

        $params = array(
                // todo prefix uuid
                'UserId' => $userInfo->uuid,
            );

        $data = $soapClient->GetUser($params);

        $returnData = json_decode($data->GetUserResult);
        $returnData->avatar_url = $userInfo->avatar_url;
        $returnData->name       = $userInfo->name;
        // 3 days
        $minutes = 3*24*60;
        Cache::put($key, $returnData, $minutes);

        return $returnData;
    }

    public static function getImageNews($id)
    {
        $key = 'image_news/'.$id;
        if (Cache::has($key)) {
            return Cache::get($key);
        }

        $client = self::getWebServiceClient();

        $parameter = array(
                'NewsId' => $id,
            );
        $data = $client->GetImgNewsInfo($parameter);

        $imageNews = json_decode($data->GetImgNewsInfoResult);

        $minutes = 10*24*60;
        Cache::put($key, $imageNews, $minutes);

        return $imageNews;
    }

    public static function getCsiArticleById($id)
    {
        $key = 'csi_articles/'.$id;
        if (Cache::has($key)) {
            return Cache::get($key);
        }

        $client = MultiplexController::getWebServiceClient();

        $parameter = array(
                'ArticleId' => $id,
            );

        $data = $client->GetArticleInfo($parameter);

        $article = json_decode($data->GetArticleInfoResult);
        // 缓存远程文章10天
        $minutes = 10*24*60;
        Cache::put($key, $article, $minutes);

        return $article;
    }

    public static function getCsiArticleBrief($id)
    {
        $article = self::getCsiArticleById($id);

        unset(

            $article->Body, $article->ShareLink, $article->KeyWord, $article->CategoryName,
            $article->CommentCount, $article->TotalPages, $article->NewDataRows

        );

        return $article;
    }

    public static function getCsiImageNews($id)
    {
        $key = 'csi_image_news/'.$id;
        if (Cache::has($key)) {
            return Cache::get($key);
        }

        $client = self::getWebServiceClient();

        $parameter = array(
                'NewsId' => $id,
            );
        $data = $client->GetImgNewsInfo($parameter);

        $imageNews = json_decode($data->GetImgNewsInfoResult);

        $minutes = 10*24*60;
        Cache::put($key, $imageNews, $minutes);

        return $imageNews;
    }

    public static function getCsiImageNewsBrief($id)
    {
        $imageNews = self::getCsiImageNews($id);

        unset(

            $imageNews->Body, $imageNews->ShareLink, $imageNews->KeyWord, $imageNews->CategoryName,
            $imageNews->CommentCount, $imageNews->TotalPages, $imageNews->NewDataRows

        );

        return $imageNews;
    }

    public static function getImageNewsBrief($id)
    {
        $imageNews = self::getImageNews($id);
        // todo
        unset($imageNews->Body, $imageNews->ShareLink);

        return $imageNews;
    }

    /**
     * 校验传递过来的 token 参数
     *
     * @return string
     *
     * @throws Rootant\Api\Exception\ValidationException
     */
    public static function validateToken()
    {
        $token = Input::get('token');

        if (strlen($token) !== 30) {
            throw new ValidationException('token 参数传递错误');
        }

        return $token;
    }

    /**
     * 第三方登陆用户的 token
     * 处理同步 oauth 表数据
     *
     * @param  string $uid 用户id
     */
    protected static function handleToken($uid)
    {
        $token = Input::get('token');

        if (strlen($token) !== 30) {
            throw new ValidationException('token 参数传递错误');
        }

        $userToken = DB::table('tmp_token');

        $userToken->where('token', $token)
                ->update(array('user_id' => $uid, 'updated_at' => date('Y-m-d H:i:s')));

        $oauthId = $userToken->where('token', $token)->first()->oauth_id;

        DB::table('oauth')
            ->where('id', $oauthId)
            ->update(array('user_id' => $uid, 'updated_at' => date('Y-m-d H:i:s')));

        // 更新第三方用户信息表
        DB::table('third_party_user_token')
            ->where('token', $token)
            ->update(array('oauth_id' => $oauthId, 'updated_at' => date('Y-m-d H:i:s')));

        $userToken->where('token', $token)->delete();
    }

    // modify remote user profile
    public static function modifyRemoteUser($uid)
    {
        $user = self::getUser($uid);

        $input = Input::only('email', 'company', 'position');

        $inputEmail    = $input['email'];
        $inputCompany  = $input['company'];
        $inputPosition = $input['position'];

        $soapClient = self::getWebServiceClient();

        $params = array(
                'UserName' => $user->UserName,
                'EMail'    => ($inputEmail === null)    ? ($user->UserEmail) : $inputEmail,
                'Company'  => ($inputCompany === null)  ? ($user->Company)   : $inputCompany,
                'Position' => ($inputPosition === null) ? ($user->Post)      : $inputPosition,
            );

        $soapClient->UpdUser($params);
    }

    /**
     * 获取匿名用户的信息
     *
     * @param  string $ip 匿名用户的ip
     * @return array
     */
    public static function anonymousUser($ip)
    {
        $name = self::getArea($ip);

        $user = new stdClass;
        $user->avatar_url = Request::root().Config::get('imagecache::paths.avatar_url_prefix').'default.png';
        $user->name = '来自'.$name.'的用户';

        return $user;
    }

    /**
     * 根据ip获取用户所在的城市信息
     *
     * @param  string $ip
     * @return string     城市名称
     */
    public static function getArea($ip)
    {
        // 根据ip地址查询地点信息的url
        $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=".$ip;

        $data = json_decode(file_get_contents($url));

        $result = '火星';
        if (is_object($data) && property_exists($data, 'city')) {
            $result = $data->city;
        }

        return $result;
    }

    public function generateCaptcha()
    {
        $token = Input::get('token');

        if (strlen($token) !== 30) {
            throw new ValidationException('token 参数传递错误。');
        }

        Captcha::create();

        $captcha = Session::get('captchaHash');

        $captchaToken = DB::table('tmp_token');
        $captchaToken->insert(
                array(
                    'captcha'    => $captcha,
                    'token'      => $token,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                )
            );
    }

    /**
     * 随机生成默认长度6位由字母、数字组成的字符串
     *
     * @param  integer $length
     * @return string          随机生成的字符串
     */
    public static function generateRandomStr($length = 6)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str   = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $str;
    }

    /**
     * [uuid description]
     * @return string
     */
    public static function uuid()
    {
        $randomStr = self::generateRandomStr(7);

        return uniqid($randomStr, true);
    }

    /**
     * 校验验证码
     *
     * @return void
     */
    public static function verifyCaptcha()
    {
        $token   = Input::get('token');
        $captcha = Input::get('captcha');

        $rules =  array('captcha' => array('required'), 'token' => array('required'));

        $validator = Validator::make(Input::only('captcha', 'token'), $rules);
        if ($validator->fails()) {
            $messages = $validator->messages();
            throw new ValidationException($messages->all());
        }

        $captchaToken = DB::table('tmp_token');
        $data = $captchaToken->where('token', $token)->first();

        if ($data === null) {
            // todo
            throw new ValidationException('无效的 token');
        }

        // todo
        $captchaToken->where('token', $token)->delete();

        if (!Hash::check(mb_strtolower($captcha), $data->captcha)) {
            throw new ValidationException('验证码填写不正确');
        }
    }

    public function generate_token()
    {
        echo self::generateToken();
    }

    /**
     * 生成30位唯一的字符串，作为临时的 token 使用
     *
     * @return string
     */
    public static function generateToken()
    {
        $randomStr = self::generateRandomStr(7);

        return uniqid($randomStr, true);
    }

    /**
     * curl 下载远程图片
     * @param  [type] $remoteUrl   [远程图片地址]
     * @param  [type] $storageDir  [本地存储相对路径文件夹]
     * @param  [type] $newFileName [description]
     * @return [string]            [返回图片路径]
     */
    public static function curlDownload($remoteUrl, $storageDir, $newFileName)
    {
        $curl = curl_init($remoteUrl);

        if (! file_exists($storageDir)) {
            @mkdir($storageDir, 0777, true);
        }

        $fp = fopen($storageDir.$newFileName, 'w');

        curl_setopt($curl, CURLOPT_FILE, $fp);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        curl_exec($curl);

        curl_close($curl);
        fclose($fp);

        return '/'.$storageDir.$newFileName;
    }

}